export function parseLyricTag(lyric, line) {
  const match = line.match(/^\[([a-zA-Z#][a-zA-Z0-9_]*):(.*)\]$/);
  if (!match)
    return false;
  switch (match[1]) {
    case 'ti':
      lyric.ti = match[2].trim();
      break;
    case 'ar':
      lyric.ar = match[2].trim();
      break;
    case 'al':
      lyric.al = match[2].trim();
      break;
    case 'by':
      lyric.by = match[2].trim();
      break;
    case 'offset':
      lyric.offset = toInt(match[2].trim());
      break;
    default:
      lyric.ext ??= {};
      lyric.ext[match[1]] = match[2].trim();
  }
  return !!match?.[1];
}

export function toInt(v) {
  if (typeof v == 'string')
    v = parseInt(v);
  if (typeof v != 'number')
    return undefined;
  if (isNaN(v))
    return undefined;
  return parseInt(v);
}


export function genLyricTag(lyric, option) {
  const buffer = [];
  const { skipEmpty = true } = option ?? {};
  //kuwo特别处理
  if (lyric.ext?.kuwo)
    buffer.push(`[kuwo:${lyric.ext.kuwo}]`);
  //常规标签
  if (!skipEmpty || lyric.ti)
    buffer.push(`[ti:${lyric.ti ?? ''}]`);
  if (!skipEmpty || lyric.ar)
    buffer.push(`[ar:${lyric.ar ?? ''}]`);
  if (!skipEmpty || lyric.al)
    buffer.push(`[al:${lyric.al ?? ''}]`);
  if (!skipEmpty || lyric.by)
    buffer.push(`[by:${lyric.by ?? ''}]`);
  if (lyric.offset)
    buffer.push(`[offset:${lyric.offset ?? ''}]`);
  //其他标签
  if (lyric.ext) {
    for (let key in lyric.ext) {
      if (key === 'kuwo')
        continue;
      if (!skipEmpty || lyric.ext[key])
        buffer.push(`[${key}:${lyric.ext[key] ?? ''}]`);
    }
  }
  return buffer;
}
